package com.zbkj.service.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.zbkj.common.constants.Constants;
import com.zbkj.common.model.member.PaidMemberCard;
import com.zbkj.common.model.order.Order;
import com.zbkj.common.model.user.User;
import com.zbkj.common.model.user.UserTag;
import com.zbkj.common.request.*;
import com.github.pagehelper.PageHelper;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.zbkj.common.exception.AppException;

import com.zbkj.common.response.*;
import com.zbkj.common.result.CommonResultCode;
import com.zbkj.common.model.agent.UserDividendRecord;
import com.zbkj.service.dao.UserDividendRecordDao;
import com.zbkj.service.service.*;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zbkj.service.util.BrandUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

/**
* @author Caiyc
* @description UserDividendRecordServiceImpl 接口实现
* @date 2025-09-17
*/
@Service
@Slf4j
public class UserDividendRecordServiceImpl extends ServiceImpl<UserDividendRecordDao, UserDividendRecord> implements UserDividendRecordService {

    @Resource
    private UserDividendRecordDao dao;
    @Autowired
    private MarketingActivityService marketingActivityService;
    @Autowired
    private OrderService orderService;
    @Autowired
    private PaidMemberOrderService paidMemberOrderService;
    @Autowired
    private UserService userService;
    @Autowired
    private UserTagService userTagService;
    @Autowired
    private PaidMemberCardService paidMemberCardService;
    @Autowired
    private SystemConfigService systemConfigService;


    @Override
    public Boolean create(UserDividendRecordSaveRequest userDividendRecordSaveRequest) {
        UserDividendRecord userDividendRecord = new UserDividendRecord();
        BeanUtils.copyProperties(userDividendRecordSaveRequest, userDividendRecord, "id");
        boolean save = save(userDividendRecord);
        if (!save) {
            throw new AppException(CommonResultCode.VALIDATE_FAILED, "添加失败");
        }
        return save;
    }

    /**
     * 分页查询用户艺呗记录表
     *
     * @param request          请求参数
     * @param pageParamRequest 分页类参数
     * @return List<UserDividendRecord>
     * @author Caiyc
     * @since 2025-09-17
     */
    @Override
    public List<UserDividendRecordPageDataResponse> getList(UserDividendRecordSearchRequest request, PageParamRequest pageParamRequest) {
        PageHelper.startPage(pageParamRequest.getPage(), pageParamRequest.getLimit());

        LambdaQueryWrapper<UserDividendRecord> lambdaQueryWrapper = Wrappers.lambdaQuery();
        lambdaQueryWrapper.eq(UserDividendRecord::getBrandId, BrandUtil.getBrandIdByUrl());
        lambdaQueryWrapper.eq(UserDividendRecord::getIsDel, false);

        lambdaQueryWrapper.orderByDesc(UserDividendRecord::getCreateTime);
        List<UserDividendRecord> userDividendRecords = dao.selectList(lambdaQueryWrapper);
        List<UserDividendRecordPageDataResponse> userDividendRecordResponses = new ArrayList<>();

        userDividendRecords.stream().forEach(x->{
            UserDividendRecordPageDataResponse userDividendRecordResponse = new UserDividendRecordPageDataResponse();
            BeanUtils.copyProperties(x, userDividendRecordResponse);
            userDividendRecordResponses.add(userDividendRecordResponse);
        });
        return userDividendRecordResponses;
    }

    /**
    * 修改用户艺呗记录表
    * @param request
    * @return
    */
    @Override
    public boolean update(UserDividendRecordSaveRequest request) {
        if (ObjectUtil.isNull(request.getId()) || request.getId() < 1) {
            throw new AppException(CommonResultCode.VALIDATE_FAILED, "请传入用户艺呗记录ID");
        }
        getByIdException(request.getId());
        UserDividendRecord userDividendRecord = new UserDividendRecord();
        BeanUtils.copyProperties(request, userDividendRecord);
        return updateById(userDividendRecord);
    }

    private UserDividendRecord getByIdException(Integer id) {
        UserDividendRecord userDividendRecord = getById(id);
        if (ObjectUtil.isNull(userDividendRecord)) {
            throw new AppException("用户艺呗记录不存在");
        }
        if (userDividendRecord.getIsDel()) {
            throw new AppException("用户艺呗记录不存在");
        }
        return userDividendRecord;
    }

    /**
    * 批量删除
    * @param idList
    * @return
    */
    @Override
    public boolean batchDelete(List<Integer> idList) {
        LambdaUpdateWrapper<UserDividendRecord> luw = Wrappers.lambdaUpdate();
        luw.set(UserDividendRecord::getIsDel, true);
        luw.in(UserDividendRecord::getId, idList);
        boolean update = update(luw);
        if (!update) {
            throw new AppException(CommonResultCode.ERROR.setMessage("批量删除用户艺呗记录失败"));
        }
        return true;
    }

    /**
    * 查询详情
    * @param id
    * @return
    */
    @Override
    public UserDividendRecordDetailResponse getDetails(Integer id) {
        LambdaQueryWrapper<UserDividendRecord> lqw = Wrappers.lambdaQuery();
        lqw.eq(UserDividendRecord::getIsDel, 0);
        lqw.eq(UserDividendRecord::getId, id);
        lqw.last("limit 1");
        UserDividendRecord userDividendRecord = this.getOne(lqw);
        if (ObjectUtil.isNotNull(userDividendRecord)) {
            UserDividendRecordDetailResponse response = new UserDividendRecordDetailResponse();
            BeanUtils.copyProperties(userDividendRecord, response);
            return response;
        }
        return null;
    }

    /**
    * 用户分红
    * @param testUid
    * @return
    */
    @Override
    public void userDividendTask(Integer testUid, String startDateStr,String endDateStr) {
        List<DividendConfigVo> dividendBaseConfig = marketingActivityService.getDividendBaseConfigs();
        dividendBaseConfig.forEach(configVo -> {
            userDividend( testUid,  startDateStr, endDateStr, configVo);
        });

    }
    public void userDividend(Integer testUid, String startDateStr,String endDateStr,DividendConfigVo dividendBaseConfig) {
        ProductOrderSearchRequest request = new ProductOrderSearchRequest();
        request.setDateLimit(startDateStr + "," + endDateStr);

        // 获取分红配置
        //DividendConfigVo dividendBaseConfig = marketingActivityService.getDividendBaseConfig();
        if (dividendBaseConfig == null || !BooleanUtil.isTrue(dividendBaseConfig.getStatus()) || CollUtil.isEmpty(dividendBaseConfig.getUserTagList())) {
            return;
        }

        if (BooleanUtil.isTrue(dividendBaseConfig.getStatus())
                && BooleanUtil.isTrue(dividendBaseConfig.getCustMer())
                && CollUtil.isNotEmpty(dividendBaseConfig.getMerList())) {
            // 指定商户
            List<Integer> merIds = dividendBaseConfig.getMerList().stream().map(MerchantIdNameResponse::getId).distinct().collect(Collectors.toList());
            request.setMerIds(CollUtil.join(merIds, ","));
        }
        ProductOrderStatResponse orderStat = orderService.getOrderStat(request,dividendBaseConfig);

        // 获取指定会员卡消费金额
        PaidMemberOrderStatResponse paidMemberOrderStat = getPaidMemberTotalAmount(dividendBaseConfig, startDateStr, endDateStr, null);

        BigDecimal totalAmount = BigDecimal.ZERO;
        // 累计商品订单资金池
        if (orderStat != null && orderStat.getPoolAmount() != null && orderStat.getPoolAmount().compareTo(BigDecimal.ZERO) > 0) {
            totalAmount = totalAmount.add(orderStat.getPoolAmount());
        }

        // 累计充值订单资金池
        if (paidMemberOrderStat != null && paidMemberOrderStat.getPoolAmount() != null && paidMemberOrderStat.getPoolAmount().compareTo(BigDecimal.ZERO) > 0) {
            totalAmount = totalAmount.add(paidMemberOrderStat.getPoolAmount());
        }
        log.info("资金池金额：{}", totalAmount);
        if (totalAmount == null || totalAmount.compareTo(BigDecimal.ZERO) <= 0) {
            return;
        }

        // 分红给具有身份的用户
        Integer brandId = dividendBaseConfig.getBrandId();
        for (DividendConfigTagVo dividendConfigTagVo : dividendBaseConfig.getUserTagList()) {
            if (!BooleanUtil.isTrue(dividendConfigTagVo.getSelected())) {
                continue;
            }
            if (dividendConfigTagVo.getDividendRatio() == null || dividendConfigTagVo.getDividendRatio().compareTo(BigDecimal.ZERO) <= 0) {
                continue;
            }
            if (dividendConfigTagVo.getMultipleRate() == null || dividendConfigTagVo.getMultipleRate().compareTo(BigDecimal.ZERO) <= 0) {
                continue;
            }
            Integer tagId = dividendConfigTagVo.getId();
            // 通过标签获取用户
            List<User> userList = userService.getListByTagId(tagId, testUid,brandId);
            if (CollUtil.isEmpty(userList)) {
                continue;
            }
            // 当前标签可分红金额
            BigDecimal amount = totalAmount.multiply(dividendConfigTagVo.getDividendRatio()).divide(BigDecimal.valueOf(100), 2, RoundingMode.DOWN);
            // 每个人分的金额
            BigDecimal userAmount = amount.divide(BigDecimal.valueOf(userList.size()), 2, RoundingMode.DOWN);
            List<UserDividendRecord> userDividendRecordList = CollUtil.newArrayList();
            Date now = new Date();

            for (User user : userList) {
                // 用户消费金额
                BigDecimal userComAmount = getAllComAmount(user.getId(), dividendBaseConfig);
                if (userComAmount.compareTo(BigDecimal.ZERO) <= 0) {
                    continue;
                }
                log.info("用户消费金额：{}/倍率={}/id={}/name={}", userComAmount, dividendConfigTagVo.getMultipleRate(), user.getId(), user.getNickname());
                // 用户可以分红金额=自己消费金额*可分红倍率(比如消费了100，倍率1.3 = 可分红100*1.3/100)
                BigDecimal maxAmount = userComAmount.multiply(dividendConfigTagVo.getMultipleRate()).setScale(2, RoundingMode.DOWN);
                if (maxAmount.compareTo(BigDecimal.ZERO) <= 0) {
                    continue;
                }

                // 用户已分红金额
                BigDecimal userDividendAmount = getUserDividendAmount(user.getId(),brandId);
                log.info("用户消费金额：maxAmount={}/userDividendAmount={}/id={}/name={}", maxAmount, userDividendAmount, user.getId(), user.getNickname());

                if (userDividendAmount.compareTo(maxAmount) >= 0) {
                    // 如果用户已完利润，则跳过
                    log.info("用户已完利润：maxAmount={}/userDividendAmount={}/id={}/name={}", maxAmount, userDividendAmount, user.getId(), user.getNickname());
                    continue;
                }
                BigDecimal curUserAmount = userAmount;
                if (userDividendAmount.add(userAmount).compareTo(maxAmount) > 0) {
                    // 分红+用户已分红金额大于可分红金额，则取可分红金额
                    curUserAmount = maxAmount.subtract(userDividendAmount);
                }
                // 检查今天是否已经分红
                if (checkToDayDividend(user.getId(),brandId)) {
                    log.info("今天已经分红：maxAmount={}/userDividendAmount={}/id={}/name={}", maxAmount, userDividendAmount, user.getId(), user.getNickname());
                    continue;
                }

                UserDividendRecord userDividendRecord = new UserDividendRecord();
                userDividendRecord.setUid(user.getId());
                userDividendRecord.setLinkId("0");
                userDividendRecord.setLinkType("dividend");
                userDividendRecord.setType(1);
                userDividendRecord.setAmount(curUserAmount);
                userDividendRecord.setBalance(user.getDividendMoney().add(curUserAmount));
                userDividendRecord.setRemark("增加资产");
                userDividendRecord.setCreateTime(now);
                userDividendRecord.setBrandId(brandId);
                userDividendRecordList.add(userDividendRecord);

                // 累加分红/艺呗
                this.addDividend(user.getId(), curUserAmount);
            }
            this.saveBatch(userDividendRecordList);
        }
        // 分红给普通用户
        if (BooleanUtil.isTrue(dividendBaseConfig.getIsNormalUser()) && dividendBaseConfig.getNormalDividendRatio() != null) {
            // 通过标签获取用户
            List<User> userList = userService.getNormalUserList(testUid,dividendBaseConfig.getBrandId());
            if (CollUtil.isEmpty(userList)) {
                return;
            }
            // 当前标签可分红金额
            BigDecimal amount = totalAmount.multiply(dividendBaseConfig.getNormalDividendRatio()).divide(BigDecimal.valueOf(100), 2, RoundingMode.DOWN);
            // 每个人分的金额
            BigDecimal userAmount = amount.divide(BigDecimal.valueOf(userList.size()), 2, RoundingMode.DOWN);
            List<UserDividendRecord> userDividendRecordList = CollUtil.newArrayList();
            Date now = new Date();

            for (User user : userList) {
                // 用户消费金额
                BigDecimal userComAmount = getAllComAmount(user.getId(), dividendBaseConfig);
                log.info("用户消费金额：{}/倍率={}/id={}/name={}", userComAmount, dividendBaseConfig.getNormalMultipleRate(), user.getId(), user.getNickname());
                if (userComAmount.compareTo(BigDecimal.ZERO) <= 0) {
                    continue;
                }
                // 用户可以分红金额=自己消费金额*可分红倍率(比如消费了100，倍率1.3 = 可分红100*1.3/100)
                BigDecimal maxAmount = userComAmount.multiply(dividendBaseConfig.getNormalMultipleRate()).setScale(2, RoundingMode.DOWN);
                if (maxAmount.compareTo(BigDecimal.ZERO) <= 0) {
                    continue;
                }

                // 用户已分红金额
                BigDecimal userDividendAmount = getUserDividendAmount(user.getId(),brandId);
                log.info("用户消费金额：maxAmount={}/userDividendAmount={}/id={}/name={}", maxAmount, userDividendAmount, user.getId(), user.getNickname());

                if (userDividendAmount.compareTo(maxAmount) >= 0) {
                    // 如果用户已完利润，则跳过
                    log.info("用户已完利润：maxAmount={}/userDividendAmount={}/id={}/name={}", maxAmount, userDividendAmount, user.getId(), user.getNickname());
                    continue;
                }
                BigDecimal curUserAmount = userAmount;
                if (userDividendAmount.add(userAmount).compareTo(maxAmount) > 0) {
                    // 分红+用户已分红金额大于可分红金额，则取可分红金额
                    curUserAmount = maxAmount.subtract(userDividendAmount);
                }
                // 检查今天是否已经分红
                if (checkToDayDividend(user.getId(),brandId)) {
                    log.info("今天已经分红：maxAmount={}/userDividendAmount={}/id={}/name={}", maxAmount, userDividendAmount, user.getId(), user.getNickname());
                    continue;
                }

                UserDividendRecord userDividendRecord = new UserDividendRecord();
                userDividendRecord.setUid(user.getId());
                userDividendRecord.setLinkId("0");
                userDividendRecord.setLinkType("dividend");
                userDividendRecord.setType(1);
                userDividendRecord.setAmount(curUserAmount);
                userDividendRecord.setBalance(user.getDividendMoney().add(curUserAmount));
                //userDividendRecord.setRemark("全民分红，增加红利");
                userDividendRecord.setRemark("增加资产");
                userDividendRecord.setCreateTime(now);
                userDividendRecord.setBrandId(brandId);
                userDividendRecordList.add(userDividendRecord);

                // 累加分红/艺呗
                this.addDividend(user.getId(), curUserAmount);
            }
            this.saveBatch(userDividendRecordList);
        }
    }

    /**
     * 获取指定会员卡消费金额
     *
     * @param dividendBaseConfig
     * @param startDateStr
     * @param endDateStr
     * @param uid
     * @return
     */
    private PaidMemberOrderStatResponse getPaidMemberTotalAmount(
            DividendConfigVo dividendBaseConfig, String startDateStr, String endDateStr, Integer uid) {
        BigDecimal totalAmount = BigDecimal.ZERO;
        PaidMemberOrderStatResponse paidMemberOrderStat = new PaidMemberOrderStatResponse();
        paidMemberOrderStat.setTotalPrice(BigDecimal.ZERO);
        paidMemberOrderStat.setPoolAmount(BigDecimal.ZERO);

        if (dividendBaseConfig == null || CollUtil.isEmpty(dividendBaseConfig.getSourceList())) {
            return paidMemberOrderStat;
        }

        for (DividendConfigSourceVo dividendConfigSourceVo : dividendBaseConfig.getSourceList()) {
            // 已勾选的会员卡
            if (BooleanUtil.isTrue(dividendConfigSourceVo.getSelected())) {
                if (dividendConfigSourceVo.getUseRatio() == null && dividendConfigSourceVo.getUseRatio().compareTo(BigDecimal.ZERO) <= 0) {
                    continue;
                }
                // 查询充值订单金额
                DividendPaidMemberOrderSearchRequest requestStat = new DividendPaidMemberOrderSearchRequest();
                requestStat.setDateLimit(startDateStr + "," + endDateStr);
                requestStat.setId(dividendConfigSourceVo.getId());
                requestStat.setUid(uid);
                requestStat.setBrandId(dividendBaseConfig.getBrandId());
                BigDecimal amount = paidMemberOrderService.getPaidMemberOrderAmount(requestStat);

                if (amount != null && amount.compareTo(BigDecimal.ZERO) > 0) {
                    // 总消费金额
                    paidMemberOrderStat.setTotalPrice(paidMemberOrderStat.getTotalPrice().add(amount));
                    // 使用金额
                    BigDecimal poolAmount = amount.multiply(dividendConfigSourceVo.getUseRatio()).divide(BigDecimal.valueOf(100), 2, RoundingMode.DOWN);
                    totalAmount = totalAmount.add(poolAmount);
                }
            }
        }

        paidMemberOrderStat.setPoolAmount(totalAmount);
        return paidMemberOrderStat;
    }

    private boolean checkToDayDividend(Integer id,Integer brandId) {
        QueryWrapper<UserDividendRecord> lqw = new QueryWrapper<>();
        lqw.lambda().eq(UserDividendRecord::getUid, id);
        lqw.lambda().eq(UserDividendRecord::getIsDel, 0);
        lqw.lambda().eq(UserDividendRecord::getType, 1);
        lqw.lambda().eq(UserDividendRecord::getLinkType, "dividend");
        lqw.lambda().eq(UserDividendRecord::getBrandId,brandId);
        lqw.apply("date_format(create_time, '%Y-%m-%d') = {0}", DateUtil.today());
        return  dao.selectCount(lqw) > 0 ? true : false;
    }

    private void addDividend(Integer id, BigDecimal curUserAmount) {
        userService.updateDividend(id, curUserAmount, Constants.OPERATION_TYPE_ADD);
    }

    @Override
    public List<UserDividendRecordFrontPageDataResponse> getMyListH5(UserDividendRecordFrontSearchRequest request, PageParamRequest pageParamRequest) {
        Integer userId = userService.getUserIdException();
        Integer brandId = BrandUtil.getBrandIdByUrl();
        PageHelper.startPage(pageParamRequest.getPage(), pageParamRequest.getLimit());

        LambdaQueryWrapper<UserDividendRecord> lambdaQueryWrapper = Wrappers.lambdaQuery();
        lambdaQueryWrapper.eq(UserDividendRecord::getBrandId, brandId);
        lambdaQueryWrapper.eq(UserDividendRecord::getIsDel, false);
        lambdaQueryWrapper.eq(UserDividendRecord::getLinkType, "dividend");
        if (request.getType() != null) {
            lambdaQueryWrapper.eq(UserDividendRecord::getType, request.getType());
        }
        lambdaQueryWrapper.eq(UserDividendRecord::getUid, userId);

        lambdaQueryWrapper.orderByDesc(UserDividendRecord::getCreateTime);
        List<UserDividendRecord> userDividendRecords = dao.selectList(lambdaQueryWrapper);
        List<UserDividendRecordFrontPageDataResponse> userDividendRecordResponses = new ArrayList<>();

        userDividendRecords.stream().forEach(x->{
            UserDividendRecordFrontPageDataResponse userDividendRecordResponse = new UserDividendRecordFrontPageDataResponse();
            BeanUtils.copyProperties(x, userDividendRecordResponse);
            userDividendRecordResponses.add(userDividendRecordResponse);
        });
        return userDividendRecordResponses;
    }


    private BigDecimal getUserDividendAmount(Integer id,Integer brandId) {
        QueryWrapper<UserDividendRecord> lqw = new QueryWrapper<>();
        lqw.select("IFNULL(sum(amount), 0) as amount");
        lqw.lambda().eq(UserDividendRecord::getUid, id);
        lqw.lambda().eq(UserDividendRecord::getIsDel, 0);
        lqw.lambda().eq(UserDividendRecord::getType, 1);
        lqw.lambda().eq(UserDividendRecord::getLinkType, "dividend");
        lqw.lambda().eq(UserDividendRecord::getBrandId,brandId);

        UserDividendRecord res = dao.selectOne(lqw);
        if (ObjectUtil.isEmpty(res)) {
            return BigDecimal.ZERO;
        }
        return res.getAmount() != null ? res.getAmount() : BigDecimal.ZERO;
    }

    /**
     * 获取用户订单+充值订单总金额
     *
     * @param uid
     * @param dividendBaseConfig
     * @return
     */
    private BigDecimal getAllComAmount(Integer uid, DividendConfigVo dividendBaseConfig) {
        ProductOrderSearchRequest request = new ProductOrderSearchRequest();
        request.setUid(uid);
        ProductOrderStatResponse orderStat = orderService.getOrderStat(request,dividendBaseConfig);

        // 获取指定会员卡消费金额
        PaidMemberOrderStatResponse paidMemberOrderStat = getPaidMemberTotalAmount(dividendBaseConfig, null, null, uid);

        BigDecimal totalAmount = BigDecimal.ZERO;
        // 累计商品订单资金池
        if (orderStat != null && orderStat.getPoolAmount() != null && orderStat.getPoolAmount().compareTo(BigDecimal.ZERO) > 0) {
            totalAmount = totalAmount.add(orderStat.getPoolAmount());
        }

        // 累计充值订单资金池
        if (paidMemberOrderStat != null && paidMemberOrderStat.getPoolAmount() != null && paidMemberOrderStat.getPoolAmount().compareTo(BigDecimal.ZERO) > 0) {
            totalAmount = totalAmount.add(paidMemberOrderStat.getPoolAmount());
        }
        log.info("资金池金额：{}", totalAmount);
        if (totalAmount == null) {
            return BigDecimal.ZERO;
        }
        return totalAmount;
    }

    @Override
    public MyDividendResponse getMyDividend() {
        // 获取昨天的日期
        LocalDate yesterday = LocalDate.now().minusDays(1);
        // 昨天开始时间：00:00:00
        LocalDateTime startDate = yesterday.atStartOfDay();
        // 昨天结束时间：23:59:59
        LocalDateTime endDate = yesterday.atTime(23, 59, 59);
        DividendConfigVo dividendBaseConfig = marketingActivityService.getDividendBaseConfig();
        String startDateStr = startDate.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        String endDateStr = endDate.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        // 获取指定会员卡消费金额
        PaidMemberOrderStatResponse paidMemberOrderStat = getPaidMemberTotalAmount(dividendBaseConfig, startDateStr, endDateStr, null);
        BigDecimal totalAmount = paidMemberOrderStat.getPoolAmount();

        log.info("昨日资金池金额：{}", totalAmount);
        MyDividendResponse response = new MyDividendResponse();
        response.setYesterdayAmount(totalAmount);

        // 当天时间
        LocalDateTime startOfDay = LocalDate.now().atStartOfDay();
        LocalDateTime endOfDay = LocalDateTime.of(LocalDate.now(), LocalTime.MAX);
        String startOfDayStr = startOfDay.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        String endOfDayStr = endOfDay.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        // 获取指定会员卡消费金额
        PaidMemberOrderStatResponse toDayPaidMemberOrderStat = getPaidMemberTotalAmount(dividendBaseConfig, startOfDayStr, endOfDayStr, null);
        BigDecimal curTotalAmount = toDayPaidMemberOrderStat.getPoolAmount();
        log.info("今日资金池金额：{}", curTotalAmount);
        response.setTodayAmount(curTotalAmount);

        // 我的艺呗
        Integer userId = userService.getUserIdException();
        LambdaQueryWrapper<User> checkWrapper = new LambdaQueryWrapper<>();
        checkWrapper.select(User::getId, User::getDividendMoney, User::getTagId);
        checkWrapper.eq(User::getId, userId);
        User user = userService.getOne(checkWrapper);
        if (ObjectUtil.isNotNull(user)) {
            response.setDividendMoney(user.getDividendMoney());
        }
        // 累计消费
        response.setUseDividend(getTotalDividend(userId, 2));
        // 累计艺呗
        response.setTotalDividend(getTotalDividend(userId, 1));
        // 冻结艺呗
        response.setFreezeDividend(BigDecimal.ZERO);

        // 分红比例
        getDividendRatio(user.getTagId(), response);

        // 身份标签
        if (response.getTagId() != null && response.getTagId() > 0) {
          /*  LambdaQueryWrapper<UserTag> checkWrapperTag = new LambdaQueryWrapper<>();
            checkWrapperTag.select(UserTag::getName);
            checkWrapperTag.eq(UserTag::getId, response.getTagId());
            UserTag userTag = userTagService.getOne(checkWrapperTag);
            if (ObjectUtil.isNotNull(userTag)) {
                response.setTagName(userTag.getName());
            }*/
            PaidMemberCard card = paidMemberCardService.getByIdException(response.getTagId());
            if (ObjectUtil.isNotNull(card)) {
                response.setTagName(card.getLabel());
            }
        }
        return response;
    }

    private BigDecimal getTotalDividend(Integer userId, Integer type) {
        QueryWrapper<UserDividendRecord> wrapper = new QueryWrapper<>();
        wrapper.select("IFNULL(sum(amount), 0) as amount");
        wrapper.lambda().eq(UserDividendRecord::getUid, userId);
        wrapper.lambda().eq(UserDividendRecord::getIsDel, false);
        wrapper.lambda().eq(UserDividendRecord::getLinkType, "dividend");
        wrapper.lambda().eq(UserDividendRecord::getType, type);
        UserDividendRecord order = dao.selectOne(wrapper);
        return order.getAmount();
    }

    private void getDividendRatio(String tagIds, MyDividendResponse response) {
        if (StrUtil.isBlank(tagIds)) {
            return;
        }
        // 获取用户配置
        DividendConfigVo dividendBaseConfig = marketingActivityService.getDividendBaseConfig();
        if (dividendBaseConfig == null || CollUtil.isEmpty(dividendBaseConfig.getUserTagList())) {
            return;
        }
        List<Integer> tagIdList = Arrays.asList(tagIds.split(",")).stream().map(x -> Integer.parseInt(x)).collect(Collectors.toList());

        Double maxRatio = 0.0;
        for (DividendConfigTagVo dividendConfigTagVo : dividendBaseConfig.getUserTagList()) {
            if (!BooleanUtil.isTrue(dividendConfigTagVo.getSelected())) {
                continue;
            }
            if (dividendConfigTagVo.getDividendRatio() == null || dividendConfigTagVo.getDividendRatio().compareTo(BigDecimal.ZERO) <= 0) {
                continue;
            }
            if (dividendConfigTagVo.getMultipleRate() == null || dividendConfigTagVo.getMultipleRate().compareTo(BigDecimal.ZERO) <= 0) {
                continue;
            }
            Integer tagId = dividendConfigTagVo.getId();
            if (!tagIdList.contains(tagId)) {
                continue;
            }
            if (dividendConfigTagVo.getDividendRatio().doubleValue() > maxRatio) {
                maxRatio = dividendConfigTagVo.getDividendRatio().doubleValue();
                response.setDividendRatio(dividendConfigTagVo.getDividendRatio());
                response.setTagId(tagId);
            }
        }
    }

    /**
     * 获取资金池金额
     * @param startDate
     * @param endDate
     * @return
     */
//    private BigDecimal getFundPoolAmount(LocalDateTime startDate, LocalDateTime endDate) {
//        // 统计金额
//        ProductOrderSearchRequest request = new ProductOrderSearchRequest();
//        String startDateStr = startDate.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
//        String endDateStr = endDate.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
//        request.setDateLimit(startDateStr + "," + endDateStr);
//        ProductOrderStatResponse orderStat = orderService.getOrderStat(request);
//
//        DividendPaidMemberOrderSearchRequest requestStat = new DividendPaidMemberOrderSearchRequest();
//        requestStat.setDateLimit(startDateStr + "," + endDateStr);
//        PaidMemberOrderStatResponse paidMemberOrderStat = paidMemberOrderService.getPaidMemberOrderStat(requestStat);
//
//        BigDecimal totalAmount = BigDecimal.ZERO;
//        if (orderStat != null && orderStat.getPoolAmount() != null && orderStat.getPoolAmount().compareTo(BigDecimal.ZERO) > 0) {
//            totalAmount = totalAmount.add(orderStat.getPoolAmount());
//        }
//        if (paidMemberOrderStat != null && paidMemberOrderStat.getPoolAmount() != null && paidMemberOrderStat.getPoolAmount().compareTo(BigDecimal.ZERO) > 0) {
//            totalAmount = totalAmount.add(paidMemberOrderStat.getPoolAmount());
//        }
//        return totalAmount;
//    }

}